<template>
  <div class="activityExpenses-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="8">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          新增
        </el-button>
        <el-upload
          style="position: relative;bottom: 5px; margin-right: 10px"
          action="#"
          :auto-upload="false"
          multiple
          :on-change="(file) => onChecksChange(file)"
          :show-file-list="false"
          >
          <el-button icon="el-icon-upload2" type="primary">导入</el-button>
        </el-upload>
        <el-button icon="el-icon-download" type="success" @click="downloadFile">
          下载模板
        </el-button>
        <el-button  type="success" @click="handleCostLog">
          费用日志
        </el-button>
        <el-link :underline="false">总金额：{{money}}</el-link>
      </vab-query-form-left-panel>

      <vab-query-form-right-panel :span="16">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keyword"
              placeholder="请输入服务商名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :data="list"
      @selection-change="setSelectRows"
    >
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="supplier_name"
        label="姓名"
        min-width="150"
      >
        <template #default="{ row }">

          <div style="display: none">
            <el-select
              v-show="!row.isEdit"
              v-model="row.supplier_id"
              placeholder="请选择服务商者"
              @change="((id) => { changeUser(id, row)})"
            >
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.supplier_name"
                :value="supplier.id"
              />
            </el-select>
          </div>
          <el-autocomplete
            v-show="row.isEdit"
            v-model="row.supplier_name"
            :fetch-suggestions="querySearch"
            placeholder="请输入供应商"
            @select="handleSelect">
          </el-autocomplete>
          <span v-show="!row.isEdit">{{row.supplier_name}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="mobile"
        label="手机号码"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input disabled v-show="row.isEdit" v-model="row.mobile" required/>
          <span v-show="!row.isEdit">{{row.mobile}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="idcard "
        label="身份证号"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input disabled v-show="row.isEdit" v-model="row.idcard" required/>
          <span v-show="!row.isEdit">{{row.idcard}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="bank"
        label="开户行"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input disabled v-show="row.isEdit" v-model="row.bank" required/>
          <span v-show="!row.isEdit">{{row.bank}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="bank_card"
        label="银行卡号"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input disabled v-show="row.isEdit" v-model="row.bank_card" required/>
          <span v-show="!row.isEdit">{{row.bank_card}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="subtotal"
        label="推广费"
        min-width="100"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.price" required/>
          <span v-show="!row.isEdit">{{row.price}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="client_name"
        label="认购客户姓名"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.client_name" required/>
          <span v-show="!row.isEdit">{{row.client_name}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="client_mobile"
        label="联系方式"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.client_mobile" required/>
          <span v-show="!row.isEdit">{{row.client_mobile}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="room_number"
        label="认购房号"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.room_number" required/>
          <span v-show="!row.isEdit">{{row.room_number}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="sign_date"
        label="签约日期"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.sign_date" required/>
          <span v-show="!row.isEdit">{{row.sign_date}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="room_money"
        label="房款总价"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.room_money" required/>
          <span v-show="!row.isEdit">{{row.room_money}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="counselor"
        label="置业顾问"
        min-width="180"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.counselor" required/>
          <span v-show="!row.isEdit">{{row.counselor}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="is_verified"
        label="是否属实"
        min-width="100"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.is_verified" required/>
          <span v-show="!row.isEdit">{{row.is_verified}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        show-overflow-tooltip
        prop="mark"
        label="备注"
      >
        <template #default="{ row }">
          <el-input v-show="row.isEdit" v-model="row.mark" required/>
          <span v-show="!row.isEdit">{{row.mark}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="175" fixed="right">
        <template #default="{ row }">
          <!--<el-button
            type="text"
            :disabled="row.is_img === 2"
            @click="showChecks(row)"
          >
            查看验收材料
          </el-button>
          -->
          <div v-show="row.isEdit">
            <el-button
              type="text"
              @click="addExpenses(row)"
            >
              保存
            </el-button>
            <el-button
              type="text"
              @click="cancelExpenses(row)"
            >
              取消
            </el-button>
          </div>
          <div v-show="!row.isEdit">
            <el-button
              type="text"
              :disabled="row.is_handler === 2"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              :disabled="row.is_handler === 2"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </div>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :page-size="queryForm.list_row"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />

    <el-dialog :visible.sync="downloadVisible" width="650px">
      <template>
        <el-link style="font-size: 20px" :underline="false">
          添加名单
        </el-link>
        <el-select
          v-model="selPerson"
          multiple
          value-key="id"
          placeholder="请选择服务商"
        >
          <el-option
            v-for="item in personOption"
            :key="item.id"
            :value="item"
            :label="item.supplier_name"
          >
          </el-option>
        </el-select>
        <el-link style="font-size: 20px; margin-left: 20px" :underline="false">
          已选人数：{{selPerson.length}}
        </el-link>
      </template>
      <el-table
        :data="selPerson"
        style="width: 100%; margin-top: 20px">
        <el-table-column
          align="center"
          type="index"
          label="序号"
        />
        <el-table-column
          align="center"
          prop="supplier_name"
          label="服务商"
        />
        <el-table-column align="center" label="操作" width="85">
          <template #default="{ row }">
            <el-button
              type="text"
              @click="handlePersonDelete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checksVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDownTemplate">下载模板</el-button>
        </div>
      </template>
    </el-dialog>

   <!-- <el-dialog title="验收材料" :visible.sync="checksVisible" width="1130px">
      <div v-if="checks.length" class="checks">
        <el-image
          v-for="(check, index) in checks"
          :key="index"
          :src="checks[index]"
          :preview-src-list="checks"
          :z-index="5000"
          class="check"
          lazy
        />
      </div>
      <div v-else>没有提交验收材料</div>
    </el-dialog>-->
  </div>
</template>

<script>
  import {
    doDelete,
    getExpenseChecks as getChecks,
    pullTempuserlist,
    getList,
    updateTemplate,
    updateExcel,
    doAdd,
    doEdit
  } from '@/api/dc_projectExpenses'
  import Edit from './components/ActivityExpensesEdit'
  import { pullTempuserlist as getSupplierList } from '@/api/dc_projectExpenses'

  export default {
    name: 'ProjectExpenses',
    components: { Edit },
    data() {
      return {
        suppliers: [],
        money: 0,   //总金额
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          activity_id: this.$route.query.activity_id,
          page: 1,
          list_row: 10,
          keyword: '',
        },
        downloadVisible: false,
        checks: [],
        personOption: [],   //可以选择的自由者
        selPerson: [],    //选择的自由者
        type: '',
        restaurants:[]
      }
    },
    created() {
      this.fetchData()
    },
    mounted() {
      let params = {
        activity_id: this.$route.query.activity_id
      }
      getSupplierList(params).then((res) => {
        console.log(123123123,res)
        this.restaurants = res;
      })
    },
    methods: {
      handleCostLog(row) {
        console.log(row)
        const { id: activity_id, activity_name } = row
        this.$router.push({
          name: 'ProjectCostLog',
          query: { activity_id, activity_name },
        })
      },
      changeUser(id, row) {
        let index = this.suppliers.findIndex((val) => val.id = id)
        row.supplier_name = this.suppliers[index].supplier_name
        row.mobile = this.suppliers[index].mobile
        row.idcard = this.suppliers[index].idcard
        row.bankCard = this.suppliers[index].bankCard
        row.bankName = this.suppliers[index].bankName
        this.list = this.list.concat([])
      },
      //编辑取消
      cancelExpenses(row) {
        if (this.type == 'add') {
          this.list.splice(0, 1)
        } else {
          row.isEdit = false
          this.list = this.list.concat([])
        }
        this.type = ''
      },
      onChecksChange(file, index) {
        // 处理待上传图片
        const formData = new FormData()
        formData.append('file', file.raw)
        // 上传图片
        updateExcel(formData, this.$route.query.activity_id).then((res) => {
          this.fetchData()
        })
      },
      handleDownTemplate() {
        if (!this.selPerson.length) {
          this.$message({
            type: "error",
            message: '请选择服务商'
          });
          return
        }
        let idArr = this.selPerson.map((val) => val.id)
        let params = {
          id: idArr.join(','),
          activity_id: this.$route.query.activity_id
        }
        updateTemplate(params).then(res => {
         location.href = res
        })
      },
      //获取选择的自由者列表
      async downloadFile() {
        const data = await pullTempuserlist({ activity_id: this.$route.query.activity_id})
        this.personOption = data
        this.downloadVisible = true
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      async addExpenses(row) {
        let msg
        this.$set(row, 'supplier_id', '')
        row.activity_id = this.$route.query.activity_id
        if (this.type === 'add') {
          this.restaurants.forEach(item =>{
            if(item.supplier_name === row.supplier_name){
              row.supplier_id = item.id
            }
          })
          msg = await doAdd(row)
        } else {
          this.restaurants.forEach(item =>{
            if(item.supplier_name === row.supplier_name){
              row.supplier_id = item.id
            }
          })
          msg = await doEdit(row)
        }
        this.type = ''
        this.fetchData()
        this.$baseMessage(msg, 'success')
      },
      handleEdit(row) {
        if(this.type != '') return
        let params = {
          activity_id: this.$route.query.activity_id
        }
        getSupplierList(params).then((res) => {
          this.suppliers = res
          if (row.id) {
            this.type = 'edit'
            row.isEdit = true
            row.activity_expenses_id = row.id
            row.number = 1
          } else {
            this.type = 'add'
            this.list.unshift({ number: 1 })
            this.list[0].isEdit = true
          }
        })
      },
      querySearch(queryString, cb) {
        console.log(231,this.restaurants)
        if (this.restaurants && this.restaurants.length>0){
          this.restaurants.forEach(item =>{
            this.$set(item, 'value', item.supplier_name)
          })
        }
        let restaurants = this.restaurants;
        let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        console.log(2222,queryString)
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
        };
      },
      handleSelect(item) {
        console.log(222,item);
      },
      handlePersonDelete(row, index) {
        this.selPerson.splice(index, 1)
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ activity_expenses_id: row.id })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.list_row = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.page = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data, money } = await getList(this.queryForm)
        this.list = data.data
        this.total = data.total
        this.money = money
        this.listLoading = false
      },
      inDev() {
        this.$message('开发中')
      },
      showChecks(row) {
        const { id: expenseId, activity_id: activityId } = row
        getChecks({ id: expenseId }).then((res) => {
          let checks = []
          res.forEach(
            (type) => (checks = [...checks, ...(type.check_img || [])]),
          )
          this.checks = checks
          this.checksVisible = true
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .table-expand {
    font-size: 0;
    ::v-deep {
      label {
        width: 120px;
        color: #99a9bf;
      }
      .el-form-item {
        width: 50%;
        margin-right: 0;
        margin-bottom: 0;
      }
    }
  }

  ::v-deep {
    .el-table__expanded-cell {
      padding: 20px 50px !important;
    }
  }

  .status-rejected {
    color: #f56c6c;
    cursor: help;
    border-bottom: 1px dashed #dcdfe6;
  }

  ::v-deep .dialog-orders {
    width: 80%;

    @media (min-width: 1440px) {
      width: 60%;
    }
  }

  .checks {
    display: flex;
    flex-wrap: wrap;
    margin-right: -10px;
    margin-bottom: -10px;
  }

  .check {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .invoice-img {
    display: block;
    margin-bottom: 18px;
  }
</style>
